﻿using Grpc.Core;
using Grpc.Net.Client;
using Grpc.Net.Client.Balancer;
using Grpc.Net.Client.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nacos.Provider.gRPC
{
    public class NacosGrpcChannel : INacosGrpcChannel
    {
        private readonly IServiceProvider serviceProvider = null;

        public NacosGrpcChannel(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }

        public GrpcChannel FromService(string serviceName)
        {
            return this.FromService(serviceName, "DEFAULT_GROUP");
        }

        public GrpcChannel FromService(string serviceName, string groupName)
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            return GrpcChannel.ForAddress("nacos://" + groupName + "/" + serviceName, new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Insecure,
                ServiceConfig = new ServiceConfig { LoadBalancingConfigs = { new LoadBalancingConfig("NacosRandom") } },
                ServiceProvider = this.serviceProvider
            });
        }
    }
}
